<template>
  <div class="address-search-input-container" ref="addressSearchRef">
    <div class="address-search-input">
      <div class="input-inner" ref="inputInnerRef">
        <input
          @focus="inputFocus"
          @blur="inputBlur"
          class="input-control"
          type="text"
          :maxlength="50"
          :value="modelValue"
          :placeholder="placeholder || $t('placeholder.search_key')"
          @keydown="inputSearch"
          @input="modelValueInput"
        />
        <IconSearch class="svg"></IconSearch>
      </div>
      <div class="tools" v-if="country || workType || profession">
        <div
          class="city"
          :class="[cityMobileSelectVisible ? 'active' : '']"
          v-if="country"
          @click.stop="onClickCitySelectButton"
        >
          <IconAddress class="svg-address"></IconAddress>
          <div>
            <span>{{ $t("tag.city") }}：</span
            >{{
              currentCity.title
                ? currentCity.title
                : $t(cityNavPanel[currentActiveIndex].label)
            }}
            <IconArrowDown class="arrow-down" />
          </div>
        </div>
        <div class="workType" v-if="workType">
          <span>{{ $t("tag.work_type") }}</span>
          <IconArrowDown></IconArrowDown>
        </div>
        <div class="profession" v-if="profession">
          <span>{{ $t("tag.industry") }}：{{ $t("tag.all") }}</span>
        </div>
      </div>
    </div>
    <div
      class="address-search-input-main"
      :class="[cityMobileSelectVisible ? 'show' : '']"
      :style="{ height: `calc(${containerRectHeight})` }"
    >
      <Transition name="slideDown">
        <div
          class="address-search-input-country"
          v-show="cityMobileSelectVisible"
        >
          <div class="select-content">
            <div class="side-country-wrapper" ref="sideCityWrapper">
              <div class="side-country">
                <div
                  class="side-country-item"
                  v-for="(item, index) in cityNavPanel"
                  :key="item.id"
                  :class="cityNavActiveId == item.value ? 'active' : ''"
                  @click="cityNavPanelItemClick(item, index)"
                >
                  {{ $t(item.label) }}
                </div>
              </div>
            </div>
            <div class="country-list-wrapper" ref="countryWrapper">
              <div class="country-list">
                <div
                  class="country-list-item"
                  v-for="item in currentCitiesData"
                  :key="item.id"
                  :class="item.id == currentCity.id ? 'active' : ''"
                  @click="onClickCityItem(item)"
                >
                  {{ item.title }}
                </div>
              </div>
            </div>
          </div>
          <div class="select-footer">
            <a-button type="default" @click="mobileCityReset">{{
              $t("btnText.reset")
            }}</a-button>
            <a-button type="primary" @click="mobileCityEnsure">{{
              $t("btnText.confirm")
            }}</a-button>
          </div>
        </div>
      </Transition>
    </div>

    <a-modal
      v-if="country"
      class="input-city-select-modal"
      width="44.1667vw"
      :footer="null"
      :closable="false"
      v-model:open="citySelectVisible"
      :title="$t('dialog.city_select.title')"
    >
      <NavPanel
        :data="cityNavPanel"
        :activeId="cityNavActiveId"
        @item-click="cityNavPanelItemClick"
        :goto="false"
        lang
      ></NavPanel>
      <div class="city-list-box">
        <div class="city-list">
          <div
            class="city-item"
            v-for="item in currentCitiesData"
            :key="item.id"
            :class="item.id == currentCity.id ? 'active' : ''"
            @click="onClickCityItem(item)"
          >
            <span>{{ item.title }}</span>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  ref,
  watch,
} from "vue";
import { useCacheStore, useGlobalStore, useMemberStore } from "../../store";
import { useTouchAction } from "../../hooks/useTouchAction";
import {
  postChinaCity,
  postForeignCity,
  postRecommendCity,
} from "../../api/api";
const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;
type Props = {
  // 双向绑定
  modelValue: string;
  countryValue: string;
  // boolean
  country: boolean;
  workType: boolean;
  profession: boolean;
  blur: boolean;
  placeholder?: string;
};

const props = withDefaults(defineProps<Props>(), {
  blur: false,
});

const emits = defineEmits([
  "select-city",
  "search",
  "update:modelValue",
  "update:countryValue",
]);

const addressSearchRef = ref();
const cacheStore = useCacheStore();
const inputInnerRef = ref();
const inputFocus = () => {
  inputInnerRef.value.classList.add("focus");
};
const inputBlur = (event: FocusEvent, flag = false) => {
  if (!props.blur && !flag) return;
  inputInnerRef.value.classList.remove("focus");
  emits("search", props.modelValue);
};

const modelValueInput = useDebounce((e: InputEvent) => {
  emits("update:modelValue", e.target.value);
  if (!isMobile()) {
    emits("search", e.target.value);
  }
}, 1000);

const inputSearch = (e: KeyboardEvent) => {
  if (e.keyCode == 13) {
    if (props.blur) {
      e.target.blur();
    } else {
      if (isMobile()) {
        inputBlur(null, true);
      }
    }
  }
};
const memberStore = useMemberStore();
const citySelectVisible = ref(false);
const cityMobileSelectVisible = ref(false);
const cityNavActiveId = ref(1);
const currentActiveIndex = ref(0);
const cityNavPanel = ref([
  { label: "dialog.city_select.country_1", value: 1 },
  { label: "dialog.city_select.country_2", value: 2 },
  { label: "dialog.city_select.country_3", value: 3 },
]);

// 当前选中的城市
const currentCity = ref({
  id: "",
  title: "",
});
// 设置选中的城市
const onClickCityItem = (item) => {
  currentCity.value.id = item.id;
  currentCity.value.title = item.title;
  if (!isMobile()) {
    citySelectVisible.value = false;
    emits("update:countryValue", item.id);
    emits("select-city", currentCity.value);
  }
};

const mobileCityEnsure = () => {
  cityMobileSelectVisible.value = false;
  emits("select-city", currentCity.value);
  emits("update:countryValue", currentCity.value.id);
  emits("search");
};

const mobileCityReset = () => {
  currentActiveIndex.value = 0;
  currentCity.value.title = "";
  currentCity.value.id = "";
  cityNavActiveId.value = 1;
  mobileCityEnsure();
};

const cityNavPanelItemClick = (item, index: number) => {
  cityNavActiveId.value = item.value;
  currentActiveIndex.value = index;
};

const sideCityWrapper = ref();
const countryWrapper = ref();
watch(cityMobileSelectVisible, (n) => {
  useTouchAction().setTouchAction();
  if (n) {
    getCityAllData();
  }
});

const containerRectHeight = ref();

const refreshContainerRectHeight = () => {
  containerRectHeight.value =
    window.innerHeight -
    (addressSearchRef.value.getBoundingClientRect().top +
      addressSearchRef.value.getBoundingClientRect().height) +
    "px";
};

const onClickCitySelectButton = () => {
  if (isMobile()) {
    cityMobileSelectVisible.value = !cityMobileSelectVisible.value;
    if (cityMobileSelectVisible.value) {
      refreshContainerRectHeight();
    }
  } else {
    citySelectVisible.value = true;
    getCityAllData();
  }
};

const onResize = () => {
  cityMobileSelectVisible.value = false;
  citySelectVisible.value = false;
};

const countriesData = ref();
const getCityAllData = async () => {
  if (countriesData.value) return;
  let res = await Promise.all([
    postRecommendCity(),
    postChinaCity(),
    postForeignCity(),
  ]);
  countriesData.value = [res[0].data, res[1].data, res[2].data];
};

const currentCitiesData = computed(() => {
  return countriesData.value && countriesData.value[currentActiveIndex.value];
});

const closeCitySelectModal = () => {
  citySelectVisible.value = false;
  cityMobileSelectVisible.value = false;
};

onMounted(() => {
  window.addEventListener("resize", onResize);
  window.addEventListener("scroll", onResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", onResize);
  window.removeEventListener("scroll", onResize);
  if (cacheStore.touchActionDiabled) {
    useTouchAction().setTouchAction();
  }
});
</script>

<style lang="less">
.input-city-select-modal {
  .ant-modal-content {
    padding: 0;
    border-radius: 20px;
    .ant-modal-header {
      border-radius: 0;
      margin-bottom: 0;
      padding: 24px;
      padding-bottom: 4px;
      .ant-modal-title {
        font-weight: 500;
      }
    }
  }
}
</style>

<style scoped lang="less">
.address-search-input {
  padding: 16px 0;
  display: flex;
  align-items: center;
  gap: 16px;
  .input-inner {
    transition: border-color 0.3s;
    &.focus {
      border-color: var(--yd-primary-color);
    }
    width: 320px;
    display: flex;
    align-items: center;
    padding: 5px 8px;
    border: 1px solid #cfd2cc;
    border-radius: 4px;
    input.input-control {
      background-color: transparent;
      margin-right: 8px;
      flex: 1;
      font-size: 16px;
      color: #c8c8c8;
      &::placeholder {
        color: #c8c8c8;
      }
    }
  }
  .tools {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    & > * {
      display: flex;
      align-items: center;
      background-color: #d1e1f8;
      border-radius: 4px;
      padding: 5px 8px;
      font-size: 16px;
      color: #323232;
      gap: 8px;
      cursor: pointer;
      &.city {
        .arrow-down {
          display: none;
        }
      }
    }
  }
}
.input-city-select-modal {
  .city-list-box {
    min-height: 360px;
    max-height: 360px;
    overflow-y: auto;
  }
  .city-list {
    padding: 24px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    row-gap: 16px;
    font-size: 16px;
    .city-item {
      display: flex;
      padding: 5px 0;
      align-items: center;
      justify-content: center;
      &.active {
        color: var(--yd-primary-color);
      }
      span {
        cursor: pointer;
      }
    }
  }
}
.address-search-input-main {
  display: none;
}

@media screen and (max-width: 768px) {
  .address-search-input-container {
    position: sticky;
    top: calc(var(--yd-header-height) + 225px);
    z-index: 9;
    .address-search-input-main {
      position: absolute;
      left: 0;
      right: 0;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      margin-left: -82px;
      margin-right: -82px;
      &.show {
        height: calc(100vh - var(--yd-header-height) - 512px - 225px);
      }
      .address-search-input-country {
        position: relative;
        z-index: 0;
        display: flex;
        flex: 1;
        height: 100%;
        flex-direction: column;
        border-top: 1px solid #ccd6de;
        .select-content {
          flex: 1;
          display: flex;
          height: calc(100% - 348px);
          .side-country-wrapper {
            background-color: #f5f5f5;
            overflow: hidden;
          }
          .side-country {
            width: 614px;
            padding: 41px 0;
            display: flex;
            flex-direction: column;
            font-size: 72px;
            .side-country-item {
              padding: 61px 82px;
              word-break: break-all;
              &.active {
                color: #3d88f2;
                font-weight: 600;
              }
            }
          }
          .country-list-wrapper {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;
            overscroll-behavior: contain;
          }
          .country-list {
            padding: 41px 61px;

            .country-list-item {
              font-size: 72px;
              padding: 61px 82px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              &.active {
                color: #3d88f2;
              }
            }
          }
        }
        .select-footer {
          display: flex;
          background-color: #fff;
          border-top: 1px solid #ccd6de;
          padding: 56px 82px;
          gap: 61px;
          :where(.css-dev-only-do-not-override-19iuou).ant-btn-default:not(
              :disabled
            ):active {
            border-color: #b8bec2 !important;
          }
          :deep(.ant-btn) {
            border-radius: 20px !important;
            height: 225px !important;
            font-size: 72px !important;
            letter-spacing: 0px !important;
            &:first-child {
              width: 410px !important;
              background-color: #e6e6e6;
              color: #323232;
            }

            &:last-child {
              flex: 1;
            }
          }
        }
      }
    }
  }
  .address-search-input {
    position: relative;
    z-index: 9;
    padding: 61px 0;
    gap: 61px;
    flex-direction: column;
    align-items: flex-start;
    background-color: #f6f8fa;
    .input-inner {
      width: 100%;
      padding: 31px 61px;
      border-radius: 20px;
      input.input-control {
        margin-right: 50px;
        font-size: 72px;
      }
      .svg {
        width: 82px;
        height: 82px;
      }
    }
    .tools {
      gap: 61px;
      & > * {
        padding: 31px 61px;
        border-radius: 20px;
        font-size: 72px;
        gap: 31px;
        & > div {
          display: flex;
          align-items: center;
          span {
            display: none;
          }
        }
        &.city {
          &.active {
            color: var(--yd-primary-color);
            :deep(.arrow-down) {
              polygon {
                fill: var(--yd-primary-color) !important;
              }
              transform: rotate(-180deg);
            }
          }
          .svg-address {
            width: 72px;
            height: 72px;
          }
          .arrow-down {
            transition: all 0.3s;
            display: block;
            width: 82px;
            height: 82px;
            margin-left: 41px;
          }
        }
      }
    }
  }
}
</style>
